package com.hnust.controller.subject;

import com.hnust.controller.subject.dialog.ModifySubjectController;
import com.hnust.domain.*;
import com.hnust.fx.DialogBuilder;
import com.hnust.fx.FXMLController;
import com.hnust.service.SubjectService;
import com.hnust.service.SubjectServices;
import com.hnust.store.DataStore;
import com.hnust.store.SubjectStore;
import com.hnust.view.subject.dialog.CheckSubjectView;
import com.hnust.view.subject.dialog.ModifySubjectView;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXRadioButton;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.util.StringConverter;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.*;

/**
 * 创建人：zhangRuWang
 * 创建时间：2021/5/8
 * 描述：
 */

@FXMLController
public class NewSubjectListController implements Initializable {
    public AnchorPane subjectListWindow;
    public ComboBox<CourseData> selectedCourse;
    public Pagination page;
    public Label dataCount;
    public Label dataRows;
    public Label dataPages;
    public VBox subjectsContainer;
    public Label courseDataLabel;
    public VBox loadingSubjectInfo;
    public JFXButton loading;
    @Autowired
    private DataStore dataStore;
    @Autowired
    private SubjectStore subjectStore;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private SubjectServices subjectServices;
    @Autowired
    private CheckSubjectView checkSubjectView;
    @Autowired
    private ModifySubjectView modifySubjectView;
    @Autowired
    private ModifySubjectController modifySubjectController;
    private String selectedCourseId;
    private int selectedCourseIndex=0;
    public Integer rows=10;
    public Integer currentPage=0;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        subjectListWindow.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                //是否是第一次加载
                if(subjectStore.isFirst()){
                    getAllCourses();
                    subjectStore.setFirst(false);
                }
            }
        });
        selectedCourse.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                selectedCourseId=newValue.getId();
                selectedCourseIndex=selectedCourse.getSelectionModel().getSelectedIndex();
                InitSubjects(currentPage,rows,null);
            }
        });
        selectedCourse.setConverter(new StringConverter<CourseData>() {
            @Override
            public String toString(CourseData object) {
                return object.getName();
            }
            @Override
            public CourseData fromString(String string) {
                return null;
            }
        });
        page.currentPageIndexProperty().addListener((observable, oldValue, newValue) -> {
            currentPage= newValue.intValue();
            InitSubjects(currentPage,rows,null);
        });
    }

    /**
     * @param subjectTest 题目对象
     * @param num 题目序号
     * @return 题目视图
     */
    public VBox genSubjectVBox(SubjectTest subjectTest,int num){
        VBox vBox=new VBox();
        vBox.getStyleClass().add("custom-table");
        //设置大盒子内容随内容的不同而伸缩
        VBox.setVgrow(vBox, Priority.ALWAYS);
        vBox.setSpacing(20);

        //添加题目介绍：序号，查看详情，题型
        HBox hBox=new HBox();
        JFXButton check=new JFXButton("查看题目详情");
        check.getStyleClass().add("modifyBtn");
        check.setDisableVisualFocus(false);
        check.setOnAction(event -> {
            subjectStore.setCheckSubject(subjectTest);
            new DialogBuilder(check).setTitle("查看题目详情").setBody(checkSubjectView.getView()).
                    setPositiveBtn("确定", "#3333cc").setSize(900.0,550.0).create();
        });

        JFXButton modify=new JFXButton("修改题目");
        modify.getStyleClass().add("resetBtn");
        modify.setOnAction(event -> {
            subjectStore.setModifySubject(subjectTest);
            new DialogBuilder(check).setTitle("修改题目").setBody(modifySubjectView.getView()).
                    setPositiveBtn("确定", () -> {
                        //修改题目，发送请求
                        if(subjectStore.isModifyHasChapter()&&subjectStore.isModifyHasTarget()){
                            modifySubjectController.setModifySubject();
                            SubjectDataInfo subjectDataInfo=subjectStore.getModifySubjectDataInfo();
                            SubjectDataReq subjectDataReq=new SubjectDataReq(
                                    subjectDataInfo,dataStore.getToken(),dataStore.getTeacher_id()
                            );
                            subjectServices.updateSubInfo(subjectDataReq,loading);
                        }else{
                            new DialogBuilder(loading).setTitle("提示").setMessage("没有课程目标或课程章节，修改失败").
                                    setPositiveBtn("确定","#ff3333").create();
                        }

                    }, "#3333cc").setNegativeBtn("取消",()->{

            },"#ff3333").setSize(900.0,550.0).create();
        });


        Label label=new Label(num+".");
        label.getStyleClass().add("label_text");

        JFXButton subjectType=new JFXButton(subjectTest.getType_name());
        subjectType.getStyleClass().add("resetBtn");
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.setSpacing(10);
        hBox.setPadding(new Insets(10,20,10,20));
        hBox.getChildren().addAll(label,check,modify,subjectType);

        //添加题目内容
        VBox subjectContentBox=new VBox();
        WebView subjectContent=new WebView();
        subjectContent.getEngine().loadContent(subjectTest.getContent());
        subjectContentBox.getChildren().add(subjectContent);
        subjectContent.setMinHeight(120);
        subjectContent.prefWidthProperty().bind(vBox.widthProperty());

        //添加答案
        VBox answers=new VBox();
        answers.setAlignment(Pos.CENTER_LEFT);
        if(subjectTest.getType_name().equals("填空题")||subjectTest.getType_name().equals("简答题")){
            HBox h=new HBox();
            HBox.setHgrow(h,Priority.ALWAYS);
            Label right=new Label("正确答案：");
            right.setMinWidth(80);
            right.getStyleClass().add("label_text");
            WebView rightContent=new WebView();
            rightContent.prefWidthProperty().bind(vBox.widthProperty());
            rightContent.setMinHeight(100);
            if(subjectTest.getAnswer()!=null){
                StringBuilder tmp= new StringBuilder();
                for(AnswerTestObj a:subjectTest.getAnswer()){
                    if(a.getRight()){
                        tmp.append(a.getContent());
                    }
                }
                rightContent.getEngine().loadContent(tmp.toString().trim());
            }
            h.getChildren().addAll(right,rightContent);
            h.setPadding(new Insets(10,0,10,20));
            answers.getChildren().add(h);
        }else{
            if(subjectTest.getAnswer()!=null){
                //使用优先队列对答案进行排序
                PriorityQueue<NewAnswer> newAnswers=new PriorityQueue<>(Comparator.comparing(NewAnswer::getContent));
                //PriorityQueue<NewAnswer> newAnswers=new PriorityQueue<>(Comparator.comparingInt(o -> o.getIndex().toCharArray()[0]));
                for(AnswerTestObj a:subjectTest.getAnswer()){
                    //System.out.println(a.getContent());
                    newAnswers.add(new NewAnswer(a.getContent().substring(3,4),a.getContent(),a.getRight()));
                }
                while(!newAnswers.isEmpty()){
                    NewAnswer as=newAnswers.poll();
                    //System.out.println(as.getIndex());
                    HBox h=new HBox();
                    HBox.setHgrow(h,Priority.ALWAYS);
                    h.setAlignment(Pos.CENTER_LEFT);
                    WebView rightContent=new WebView();
                    rightContent.getEngine().loadContent(as.getContent());
                    rightContent.setMinHeight(35);
                    JFXRadioButton rb=new JFXRadioButton();
                    rb.setStyle("-fx-pref-height: 40;-fx-font-size: 1.1em");
                    if(as.isRight()){
                        rb.setSelected(true);
                    }
                    rb.setDisable(true);
                    h.getChildren().addAll(rb,rightContent);
                    h.setPadding(new Insets(10,0,10,20));
                    answers.getChildren().add(h);
                }
            }
        }
        //加入题目容器
        vBox.getChildren().addAll(hBox,subjectContentBox,answers);
        return vBox;
    }

    public void InitSubjects(int currentPage, Integer rows, String keyword) {
        subjectServices.getCourseSub(currentPage,rows,keyword,loading,selectedCourseId,
                loadingSubjectInfo,subjectsContainer);
    }

    private void getAllCourses() {
        subjectServices.getCourseData(courseDataLabel,selectedCourse,selectedCourseIndex, null);
    }

    public void setSubjectsTable(int total){
        int a=total/rows;
        if(total%rows!=0){
            a++;
        }
        page.setPageCount(a);
        dataCount.setText("共有"+total+"条数据");
        dataPages.setText("共"+a+"页");
    }

    public void resetSubjectsTable(){
        page.setPageCount(1);
        dataCount.setText("共有0条数据");
        dataPages.setText("共0页");
    }
}
